package com.pg.agent.engine.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.pg.agent.engine.client.bo.ComponentAllInParamBO;
import com.pg.agent.engine.client.bo.ComponentInParamBO;
import com.pg.agent.engine.client.bo.InterfaceBO;
import com.pg.agent.engine.client.common.enums.ControllerTypeEnum;
import com.pg.agent.engine.client.component.APIComponent;
import com.pg.agent.engine.client.dto.InterfaceParam;
import com.pg.agent.engine.client.dto.SOPCallVO;
import com.pg.agent.engine.client.message.InPutMessage;
import com.pg.agent.engine.client.model.*;
import com.pg.agent.engine.client.model.agent.AIAgent;
import com.pg.agent.engine.client.model.environment.AIEnvironment;
import com.pg.agent.engine.client.model.llm.CallLog;
import com.pg.agent.engine.client.model.sop.*;
import com.pg.agent.engine.client.model.state.AIState;
import com.pg.agent.engine.client.model.state.RuleConvert;
import com.pg.agent.engine.client.vo.ComponentInParamType;
import com.pg.agent.engine.client.vo.HttpParam;
import com.pg.agent.engine.service.OutParamContext;
import com.pg.agent.engine.service.service.AIEnvironmentService;
import com.pg.agent.engine.service.service.AISOPService;
import com.pg.agent.engine.service.utils.*;
import com.pg.base.exception.BizException;
import com.pg.base.util.PgMathUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AISOPServiceImpl implements AISOPService {

    @Resource
    private MilvusUtils milvusUtils;

    @Resource
    private AIEnvironmentService aiEnvironmentService;


//    @Override
//    public void next(AIAgentSession session, ManagerObject managerObject, HttpServletResponse response) {
//
//        AIEnvironment aiEnvironment = session.getEnvironment();
//        AISOP aiSOP = session.getSop();
//        List<Memory> memoryList = null;
//        String relevantHistory = null;
//
//        // 获取要执行的State
//        AIState nextState = transitState(null, response);
//
//        if (nextState == null) {
//            return;
//        }
//        // 如果状态是结束状态，则直接返回结束。
//        if (nextState.getName().equals(aiSOP.getFinishStateName())) {
//            aiSOP.setFinished(true);
//            return;
//        }
//
//        session.setState(nextState);
//        aiSOP.setCurrentState(nextState);
//
//        // 按规则配置获取要执行的Agent
//        AIAgent nextAgent = routeAgent(null, memoryList, relevantHistory, response);
//
//        if (nextAgent == null) {
//            return;
//        }
//        nextState.setCurrentAgent(nextAgent.getName());
//        session.setAgent(nextAgent);
//
//        managerObject.setAiEnvironment(aiEnvironment);
//        managerObject.setAiSOP(aiSOP);
//    }

    @Override
    public void next(InPutMessage message, SessionObject sessionObject, HttpServletResponse response) {

        AIEnvironment aiEnvironment = message.getEnvironment();
        AISOP aiSOP = message.getSop();

        // 获取要执行的State
        AIState nextState = transitState(message, response);

        if (nextState == null) {
            return;
        }
        // 如果状态是结束状态，则直接返回结束。
        if (nextState.getName().equals(aiSOP.getFinishStateName())) {
            aiSOP.setFinished(true);
            return;
        }

        message.setState(nextState);
        aiSOP.setCurrentState(nextState);

        // 按规则配置获取要执行的Agent
        AIAgent nextAgent = routeAgent(message, response);

        if (nextAgent == null) {
            return;
        }
        nextState.setCurrentAgent(nextAgent.getName());
        message.setAgent(nextAgent);
        message.getState().setCurrentAgent(nextAgent.getName());

        sessionObject.setAiEnvironment(aiEnvironment);
        sessionObject.setAiSOP(aiSOP);
    }


    private AIAgent routeAgent(InPutMessage message, HttpServletResponse response) {

        AIEnvironment aiEnvironment = message.getEnvironment();
        AIState currentState = message.getState();
        AIAgent aiAgent = null;
        CallLog callLog = new CallLog(currentState.getName(), "Agent指派");

        //  当前要执行的state是首次执行。
        if (currentState.isBegin() && currentState.getBeginAgent() != null) {
            aiEnvironment.setCurrentChatHistoryIdx(aiEnvironment.getShareMemory().getLongMemory().size());

            aiAgent = currentState.getAgent(currentState.getBeginAgent());
            currentState.setIndex(0);
            currentState.setCurrentRole(aiAgent.getRole());
            message.addCallLog(callLog, "指派模式，默认执行agent：" + aiAgent.getName());

            return aiAgent;
        }
        long agentCount = currentState.getAiAgentList().stream().filter(aiAgent1 -> !aiAgent1.isUser()).count();
        List<AIAgent> aiAgentList = currentState.getAiAgentList().stream().filter(agent -> !agent.isUser()).collect(Collectors.toList());
        if (agentCount == 1) {
            // 按对话顺序流程。所有走按order方式
            aiAgent = getOrderAiAgent(currentState.getCurrentAgent(), aiAgentList);
            message.addCallLog(callLog, "指派模式，只有一个代理，agent：" + aiAgent.getName());
        } else {
            IntentRecognition recognition = currentState.getIntentRecognition();
            Integer agentConvertType = recognition.getType();

            // 未制定Agent指派顺序，默认按顺序

            if (agentConvertType == null) {
                agentConvertType = ControllerTypeEnum.LLM.getValue();
            }
            if (Objects.equals(ControllerTypeEnum.ORDER.getValue(), agentConvertType)) {
                // 按顺手执行。

                aiAgent = getOrderAiAgent(currentState.getCurrentAgent(), aiAgentList);
                message.addCallLog(callLog, "指派模式：" + ControllerTypeEnum.ORDER.getDesc() + ", agent：" + aiAgent.getName());

            } else if (Objects.equals(ControllerTypeEnum.RANDOM.getValue(), agentConvertType)) {
                // 随机生成一个下标
                Integer index = PgMathUtil.generateRandom(currentState.getAiAgentList().size());
                aiAgent = currentState.getAiAgentList().get(index);
                message.addCallLog(callLog, "指派模式：" + ControllerTypeEnum.ORDER.getDesc() + ", agent：" + aiAgent.getName());

            } else if (Objects.equals(ControllerTypeEnum.LLM.getValue(), agentConvertType)) {

                // 通过大模型指派Agent
                aiAgent = getAiAgentByLLM(message, currentState, callLog);
                callLog.setTimeLong();
                callLog.setResponse("指派模式：大模型, agent：" + (aiAgent != null ? aiAgent.getName() : ""));

            } else if (Objects.equals(ControllerTypeEnum.RULE.getValue(), agentConvertType)) {
                IntentRecognition intentRecognition = currentState.getIntentRecognition();
                List<RuleConvert> ruleConvertList = intentRecognition.getRuleConvertList();
                String nextAgentName = null;
                for (RuleConvert ruleConvert : ruleConvertList) {
                    Integer type = ruleConvert.getType();
                    JSONObject result = null;
                    if (1 == type) {
                        APIComponent apiComponent = ruleConvert.getComponent();
                        getComponentInParam(message, ruleConvert, callLog);
                        result = executeComponent(callLog, apiComponent, message, response);
                    } else if (2 == type) {
                        JSONObject userParam = message.getUserParam();
                        result = JSONObject.parseObject(JSONObject.toJSONString(userParam));
                    }

                    Map<String, Object> expressResult = executeExpress(ruleConvert, result, message);
                    if (expressResult != null) {
                        nextAgentName = (String) expressResult.get("result");
                        if (StringUtils.isNotEmpty(nextAgentName) && !nextAgentName.equals("null")) {
                            break;
                        }
                    }
                }
                aiAgent = currentState.getAgent(nextAgentName);
                callLog.setResponse("指派模式：组件, agent：" + (aiAgent != null ? aiAgent.getName() : ""));
                callLog.setTimeLong();
            }
        }
        return aiAgent;

    }

    private Map<String, Object> executeExpress(RuleConvert ruleConvert, JSONObject result, InPutMessage inPutMessage) {
        try {

            //Map<String, Object> flatMap = JSONUtils.flattenJson(result);
            Map<String, Object> flatMap = new LinkedHashMap<>();
            if (2 == ruleConvert.getType()) {
                JSONUtils.flattenJson("", result, flatMap);
            }else if (1 == ruleConvert.getType()){
                JSONUtils.flattenJson("root", result, flatMap);
            }else if (ruleConvert.getType() == 3) {
                flatMap = getRunSystemParam(inPutMessage, inPutMessage.getQuery());
            }
        } catch (Exception e) {
            log.info("执行决策流失败：{}", e);
        } finally {
        }
        return null;
    }


    private AIAgent getAiAgentByLLM(InPutMessage message, AIState currentState, CallLog callLog) {
        AIAgent aiAgent;
        String environmentSummary = message.getEnvironment().getShareMemory().getShortMemory();
        List<Memory> chatHistory = message.getEnvironment().getRecentlyMemory();
        executeLLM(message, message.getSop(), callLog, environmentSummary, chatHistory, currentState.getIntentRecognition(), message.getQuery());
        String nextAgentName = ComponentLLMUtil.extractResult(callLog.getResponse(), currentState.listAgentName());
        aiAgent = currentState.getAgent(nextAgentName);
        log.info("Agent指派 大模型返回结果：{},解析结果：{}", callLog.getResponse(), nextAgentName);

        return aiAgent;
    }

    /**
     * 转换state
     *
     * @param message
     * @return
     */
    private AIState transitState(InPutMessage message, HttpServletResponse response) {
        AISOP aisop = message.getSop();
        AIState currentState = message.getSop().getCurrentState();


        AIState nextState = null;
        String callName = currentState == null ? "初始" : currentState.getName();
        CallLog callLog = new CallLog(callName, "State切换");


        // 如果SOP是第一次执行，则进入该状态（SOP默认状态）

        if (aisop.getStateList().size() == 1) {
            nextState = aisop.getStateList().get(0);
            message.addCallLog(callLog, "切换模式：只有一个状态, 状态：" + nextState.getName());
            return nextState;
        }

        IntentRecognition recognition = aisop.getIntentRecognition();
        Integer controllerType = recognition.getType();

        if (controllerType == null) {
            controllerType = ControllerTypeEnum.LLM.getValue();
        }
        if (ControllerTypeEnum.ORDER.getValue().equals(controllerType)) {
            int index = 0;
            for (int i = 0; i < aisop.getStateList().size(); i++) {
                AIState aiState = aisop.getStateList().get(i);
                if (aiState.getName().equals(currentState.getName())) {
                    index = i + 1;
                    break;
                }
            }
            if (index >= aisop.getStateList().size()) {
                index = 0;
            }
            nextState = aisop.getStateList().get(index);
            message.addCallLog(callLog, "切换模式：" + ControllerTypeEnum.ORDER.getDesc() + ", 状态：" + nextState.getName());

        } else if (ControllerTypeEnum.RANDOM.getValue().equals(controllerType)) {

            Set<String> keySet = aisop.getStates().keySet();
            List<String> keyList = new ArrayList<>(keySet);
            // 随机生成一个下标
            Integer index = PgMathUtil.generateRandom(keyList.size());
            nextState = aisop.getStates().get(keyList.get(index));

            message.addCallLog(callLog, "切换模式：" + ControllerTypeEnum.RANDOM.getDesc() + ", 状态：" + nextState.getName());

        } else if (ControllerTypeEnum.LLM.getValue().equals(controllerType)) {
            String environmentSummary = message.getEnvironment().getShareMemory().getShortMemory();
            List<Memory> chatHistory = message.getEnvironment().getRecentlyMemory();
            executeLLM(message, aisop, callLog, environmentSummary, chatHistory, aisop.getIntentRecognition(), message.getQuery());
            List<String> stateList = aisop.getStateList().stream().map(AIState::getName).collect(Collectors.toList());
            String nextStateStr = ComponentLLMUtil.extractResult(callLog.getResponse(), stateList);
            if (StringUtils.isEmpty(nextStateStr)) {
                String result = callLog.getResponse();
                if (currentState != null && result.contains(currentState.getName())) {
                    nextStateStr = currentState.getName();
                } else {
                    for (String stateName : stateList) {
                        if (result.contains(stateName)) {
                            nextStateStr = stateName;
                            break;
                        }
                    }
                }
            }
            nextState = aisop.getStates().get(nextStateStr);

            callLog.setResponse("切换模式：大模型，状态：" + (nextState != null ? nextState.getName() : ""));
            callLog.setTimeLong();
            message.addCallLog(callLog, "切换模式：" + ControllerTypeEnum.LLM.getDesc() + ", 状态：" + (nextState != null ? nextState.getName() : ""));

        } else if (ControllerTypeEnum.RULE.getValue().equals(controllerType)) {
            List<RuleConvert> list = recognition.getRuleConvertList();
            String nextStateStr = null;
            for (RuleConvert ruleConvert : list) {
                APIComponent apiComponent = ruleConvert.getComponent();
                getComponentInParam(message, ruleConvert, callLog);
                JSONObject result = executeComponent(callLog, apiComponent, message, response);
                //Map<String, Object> expressResult = executeExpress(ruleConvert, result, message);
            /*    if (expressResult != null) {
                    nextStateStr = (String) expressResult.get("result");
                    if (StringUtils.isNotEmpty(nextStateStr) && !nextStateStr.equals("null")) {
                        break;
                    }
                }*/
            }
            nextState = aisop.getStates().get(nextStateStr);
            callLog.setTimeLong();
            callLog.setResponse("切换模式：组件，状态：" + (nextState != null ? nextState.getName() : ""));
            message.addCallLog(callLog, "切换模式：" + ControllerTypeEnum.RULE.getDesc() + ", 状态：" + (nextState != null ? nextState.getName() : ""));

        }
        return nextState;
    }

    private void executeLLM(InPutMessage message, AISOP aisop, CallLog callLog, String environmentSummary, List<Memory> chatHistory, IntentRecognition recognition, String input) {
        StringBuilder systemPrompt = new StringBuilder();
        systemPrompt.append("当前背景为:");
        if (StringUtils.isNotEmpty(aisop.getDescription())) {
            systemPrompt.append(aisop.getDescription());
        }
//        systemPrompt.append("\n");
//        systemPrompt.append("这是最近的聊天总结:");
//        if (aisop.isSummaryHistory()) {
//            systemPrompt.append(environmentSummary).append("\n");
//        }
        systemPrompt.append("\n");
        systemPrompt.append("这是最近的历史聊天记录:");
        if (recognition.isHistoryMessage()) {
            String chatHistoryMessage = Memory.getChatHistory(chatHistory);
            systemPrompt.append(chatHistoryMessage);
        }
        systemPrompt.append("\n").append("请严格按照输出样式输出。输出样式为：<end>XXX</end>");

        List<KeyWordRelName> list = recognition.getKeyWordRelNameList();
        StringBuilder userPrompt = new StringBuilder();
        userPrompt.append("这是用户的提问：\"").append(input).append("\"\n").append("。请分析用户意图").append("\n");
        for (KeyWordRelName keyWordRelState : list) {
            userPrompt.append("若用户问题有关键字\"").append(keyWordRelState.getKeyWord()).append("\",").append("则输出<end>").append(keyWordRelState.getName()).append("</end>").append("\n");
        }
        userPrompt.append("没有则输出</end>无</end>");
        ComponentLLMUtil.callConvert(callLog, recognition.getLlm(), message, userPrompt.toString(), systemPrompt.toString());
    }


    private void getAllComponentOutParam(List<ComponentOutParam> list, List<ComponentOutParam> all, String paramCode) {
        if (!CollectionUtil.isEmpty(list)) {
            for (ComponentOutParam component : list) {
                String newParamCode = paramCode + component.getNewParamCode();
                component.setNewParamCode(newParamCode);
                getAllComponentOutParam(component.getChildren(), all, newParamCode);
                component.setChildren(null);
                all.add(component);
            }
        }
    }

    private JSONObject executeComponent(CallLog callLog, APIComponent apiComponent, InPutMessage message, HttpServletResponse response) {
        List<InterfaceBO> list = apiComponent.getInterfaceBOList();

        callLog.setCallStartTime(new Date());
        String resultMessage = "";
        String chainName = null;
        try {
            //保存执行每个API的结果
            OutParamContext outParamContext = new OutParamContext();
            chainName = String.valueOf(System.currentTimeMillis());
            outParamContext.setChainName(chainName);
            outParamContext.setCreateTime(new Date());
            Map<String, InterfaceBO> inParam = list.stream().collect(Collectors.toMap(e -> String.valueOf(e.getInterfaceId()), e -> e, (a, b) -> a));
            if (list.size() == 1) {
                InterfaceBO interfaceBO = list.get(0);
                List<InParam> inParamList = interfaceBO.getInParamList();
                HttpParam httpParam = HttpParam.instance("POST",inParamList);
                log.info("参数入参：{}", JSONObject.toJSONString(inParamList));
                callLog.setArguments(JSONObject.toJSONString(inParamList));
                callLog.addToLogInfo("请求路径", interfaceBO.getUrl());
                callLog.addToLogInfo("请求参数", JSONObject.toJSONString(inParamList));

                if (apiComponent.getType() != null && apiComponent.getType() == 1) {
                    log.info("==========使用的是流式调用=============");
                    ConvertSSEListener sseListener = new ConvertSSEListener(httpParam, message, response, message.getMessageId(), new SOPCallVO(), false);
                    ExecuteSSEUtil.executeConvertComponentSSE(interfaceBO.getUrl(), sseListener,httpParam);
                    JSONObject object = JSONObject.parseObject(sseListener.getJsonValue());
                    JSONObject data = object.getJSONObject("data");
                    data.put("content", sseListener.getOutput().toString());
                    resultMessage = JSONObject.toJSONString(object);
                    outParamContext.getMap().put(String.valueOf(interfaceBO.getInterfaceId()), object);
                } else {
                    resultMessage = HttpClientUtils.exeHttpCall(interfaceBO,httpParam);
                    outParamContext.getMap().put(String.valueOf(interfaceBO.getInterfaceId()), JSONObject.parseObject(resultMessage));
                }
            } else {
            }
            List<ComponentOutParam> componentOutParamList = JSONObject.parseArray(apiComponent.getOutParam(), ComponentOutParam.class);
            List<ComponentOutParam> allList = new ArrayList<>();
            getAllComponentOutParam(componentOutParamList, allList, "");

            JSONObject jsonObject = new JSONObject();
            for (ComponentOutParam outParam : allList) {
                Long apiId = outParam.getId();
                JSONObject apiResult = outParamContext.getMap().get(String.valueOf(apiId));
                Map<String, Object> flattMap = JSONUtils.flattenJson(apiResult);
                if (outParam.getNewParamCode().startsWith("root")) {
                    jsonObject.put(outParam.getNewParamCode(), flattMap.get(outParam.getNewParamCode().replaceFirst("root", "")));
                } else {
                    jsonObject.put(outParam.getNewParamCode(), flattMap.get(outParam.getNewParamCode()));
                }
            }
            return jsonObject;

        } catch (Exception e) {
            log.info("执行组件失败：{}", e.getMessage());
            resultMessage = "执行组件失败:" + e.getMessage();
            throw new BizException(1000, "执行组件失败:" + e.getMessage());
        } finally {
            callLog.addToLogInfo("请求结果", resultMessage);
            message.addCallLog(callLog, resultMessage);
        }

    }

    ComponentAllInParamBO getComponentInParam(InPutMessage message, RuleConvert ruleConvert, CallLog callLog) {
        ComponentAllInParamBO componentAllInParamBO = new ComponentAllInParamBO();
        String input = message.getQuery();

        APIComponent apiComponent = ruleConvert.getComponent();
        List<ComponentInParam> componentInParamList = JSONObject.parseArray(apiComponent.getInParam(), ComponentInParam.class);

        componentInParamList = Optional.ofNullable(componentInParamList).orElse(new ArrayList<>());
        List<ComponentInParam> type2 = new ArrayList<>();
        for (ComponentInParam component : componentInParamList) {
            if (component.getTypeList() != null && component.getTypeList().stream().anyMatch(p -> p.getType() == 2)) {
                type2.add(component);
            }
        }

        JSONObject argument = new JSONObject();
        // 如果存在大模型提取类型
        if (type2.size() > 0) {
            argument = extractParamByLLM(message, callLog, apiComponent, input, argument);
        }

        Map<String, Object> systemParam = getRunSystemParam(message, input);
        List<InterfaceBO> list = apiComponent.getInterfaceBOList();
        Map<Long, List<InParam>> jsonObjectMap = new HashMap<>();
        for (InterfaceBO interfaceBO : list) {
            Long interfaceId = interfaceBO.getInterfaceId();
            List<ComponentInParam> interfaceParam = componentInParamList.stream().filter(e -> e.getId().longValue() == interfaceId.longValue()).collect(Collectors.toList());
            List<InterfaceParam> interfaceParams = new ArrayList<>();
            ComponentInParamBO component = getInParam(systemParam, message, argument, interfaceParam);
            jsonObjectMap.put(interfaceId, component.getInParamList());
            interfaceBO.setInParamList(component.getInParamList());
            interfaceBO.setInterfaceParamList(interfaceParams);
        }
        componentAllInParamBO.setInParamMap(jsonObjectMap);
        return componentAllInParamBO;
    }


    private static ComponentInParamBO getInParam(Map<String, Object> systemParam, InPutMessage message, JSONObject argument, List<ComponentInParam> interfaceParam) {
        ComponentInParamBO componentInParamBO = new ComponentInParamBO();
        List<InParam> inParamList = new ArrayList<>();
        List<ComponentInParam> list = new ArrayList<>();
        for (ComponentInParam component : interfaceParam) {
            String paramCode = component.getParamCode();
            InParam inParam = BeanUtil.copyProperties(component, InParam.class);
            if ("userId".equals(paramCode)) {
                inParam.setParamValue(message.getUserId());
                continue;
            } else if ("sopId".equals(paramCode)) {
                inParam.setParamValue(message.getSop().getId());
                continue;
            } else if ("user_id".equals(paramCode)) {
                inParam.setParamValue(message.getUserId());
                continue;
            }
            List<ComponentInParamType> typeList = component.getTypeList();
            for (ComponentInParamType componentInParamType : typeList) {
                int type = componentInParamType.getType();
                //类型 1.默认值 2.大模型提取，3.用户输入。4.组件输入。
                switch (type) {
                    case 1:
                        if ("true".equals(componentInParamType.getDefaultValue()) || "false".equals(componentInParamType.getDefaultValue())) {
                            boolean result = componentInParamType.getDefaultValue().equals("true");
                            inParam.setParamValue(result);
                        } else {
                            inParam.setParamValue(componentInParamType.getDefaultValue());
                        }
                        break;
                    case 2:
                        if (!inParamList.contains(inParam)) {
                            if (argument.containsKey(paramCode)) {
                                inParam.setParamValue(argument.get(paramCode));
                            }
                        }
                        break;
                    case 6:
                        if (!inParamList.contains(inParam)) {
                            inParam.setParamValue(systemParam.get(componentInParamType.getParamCode()));
                        }
                        break;
                    case 7:
                        if (!inParamList.contains(inParam)) {
                            JSONObject customerParam = message.getUserParam();
                            inParam.setParamValue(customerParam.get(componentInParamType.getParamCode()));
                        }
                        break;
                }

                inParamList.add(inParam);
            }
        }
        componentInParamBO.setInParamList(inParamList);
        componentInParamBO.setComponentInParamList(list);
        return componentInParamBO;
    }

    private Map<String, Object> getRunSystemParam(InPutMessage message, String input) {
        Map<String, Object> map = new HashMap<>();
        map.put("query", input);
        map.put("user_id", message.getUserId());
        map.put("userId", message.getUserId());
        map.put("sopId", message.getSop());
        List<JSONObject> history = (List<JSONObject>) AIAgentServiceImpl.getHistory(message, 10).get("list");
        map.put("chat_history_message", history);

        String lastAnswer = "";
        if (history != null && history.size() > 0) {
            int size = history.size();
            for (int i = size - 1; i >= 0; i--) {
                JSONObject jsonObject = history.get(i);
                if (!jsonObject.getString("sendRole").equalsIgnoreCase("user")) {
                    lastAnswer = jsonObject.getString("content");
                    break;
                }
            }
        }
        map.put("lastAnswer", lastAnswer);
        map.put("imageList", message.getImageList());
        map.put("fileList", message.getFileList());
        return map;
    }

    private AIAgent getOrderAiAgent(String preAgentName, List<AIAgent> aiAgentList) {
        AIAgent aiAgent;
        int index = 0;
        for (int i = 0; i < aiAgentList.size(); i++) {
            AIAgent aiAgent1 = aiAgentList.get(i);
            if (aiAgent1.getName().equals(preAgentName)) {
                index = i + 1;
                break;
            }
        }
        if (index >= aiAgentList.size()) {
            index = 0;
        }
        aiAgent = aiAgentList.get(index);
        return aiAgent;
    }


    /**
     * 获取相关向量
     *
     * @param environment
     * @param sessionId
     * @return
     */
    public String getRelevantHistory(AIEnvironment environment, String sessionId) {

        ShareMemory shareMemory = environment.getShareMemory();
        List<Memory> longTermMemory = shareMemory.getLongMemory();
        Memory memory = longTermMemory.get(longTermMemory.size() - 1);
        List<Double> chatEmbedding = memory.getChatEmbeddings();

        String relevantHistory = "";
        if (longTermMemory.size() < 10) {
            return relevantHistory;
        }
        String expr = "session_id == '" + sessionId + "'";
        if (chatEmbedding != null && chatEmbedding.size() > 0) {
           // relevantHistory = milvusUtils.getRelevantHistory(chatEmbedding, expr, 3, null, longTermMemory.size());
        } else {
            List<Double> currentEmbedding = aiEnvironmentService.getEmbedding(environment, memory.getContent());
            if (currentEmbedding != null) {
                //relevantHistory = milvusUtils.getRelevantHistory(currentEmbedding, expr, 3, null, 10);
                memory.setChatEmbeddings(currentEmbedding);
            }
        }
        return relevantHistory;
    }

    private static JSONObject extractParamByLLM(InPutMessage message, CallLog callLog, APIComponent apiComponent, String input, JSONObject argument) {
        Map<String, Property> properties = new HashMap<>();
        List<String> required = new ArrayList<>();
        Parameters funParameters = new Parameters("object");
        funParameters.setProperties(properties);
        funParameters.setRequired(required);
        List<Function> functionList = new ArrayList<>();
        Function function = new Function();
        function.setName(apiComponent.getCode());
        function.setDescription(apiComponent.getDescription());
        function.setParameters(funParameters);
        functionList.add(function);

        List<Memory> memoryList = new ArrayList<>();
        Memory memory = new Memory();
        memory.setContent(input);
        memory.setSendName("agent");
        memoryList.add(memory);

        String newSystemPrompt = "现在你是一个参数提取助手。" + "\n 组件描述：" + apiComponent.getDescription();
        String newLastPrompt = "提示从用户输入获取";

        String argumentStr = null;

        //收集组装数据
        ComponentLLMUtil.callBack(callLog, message.getSop().getComLLM(), message, memoryList, newSystemPrompt, newLastPrompt, functionList);
        if (callLog.getArguments() != null) {
            argumentStr = callLog.getArguments();
            log.info("argumentStr:{}", argumentStr);
        }

        if (argumentStr != null) {
            argument = JSONObject.parseObject(argumentStr);
        }
        return argument;
    }
}